<?php

namespace App\weapp\controller;

use App\model\CustomerModel;
use App\model\EmployeeModel;
use App\model\User;
use App\model\CoinsLog;
use App\services\Pinyin;
use support\Request;

class IndexController extends Controller
{

    public function login(Request $request)
    {
        $data = $request->only(['username', 'password']);
        $validator = validator($data, [
            'username' => 'required',
            'password' => 'required'
        ], [
            'username.required' => '请输入帐号',
            'password.required' => '请输入密码'
        ]);
        if ($validator->fails()) return error($validator->errors()->first());
        $user = EmployeeModel::where('phone', $data['username'])->first();
        if( empty($user)) return error('用户不存在');
        if(!password_verify($data['password'], $user->pwd)){
            return error('密码错误');
        }
        $token = generate_user_token(['id'=>$user->id]);
        $user->login_at = date('Y-m-d H:i:s');
        $user->save();
        return success('登录成功', ['token' => $token]);
    }

    public function loginByCode(Request $request)
    {
        $code = $request->input('code', '');
        if(empty($code)) return error('需要code');
        $res = $this->wx()->auth->session($code);
        if(empty($res['openid'])) return error('登录失败');
        EmployeeModel::updateOrInsert(
            ['openid'=> $res['openid']],
            [
                'openid' => $res['openid']
            ]
        );
        $user = EmployeeModel::where('openid', $res['openid'])->first();
        if( empty($user)) return error('用户不存在');
        $token = generate_user_token(['id'=>$user->id]);
        $user->login_at = date('Y-m-d H:i:s');
        $user->save();
        return success('登录成功', ['token' => $token]);
    }

    /**
     * 上传文件
     */
    public function upload(Request $request)
    {
        $file = $request->file('file');
        if ($file && $file->isValid()) {
            $savePath = '/upload/'.date('Ymd').'/'.md5(uniqid()).'.'.$file->getUploadExtension();
            $file->move(public_path().$savePath);
            return success('上传成功', ['url' => $savePath]);
        }
        return error('文件不存在');
    }

    public function shuamingzi(){
        $users = CustomerModel::get();
        foreach ($users as $user){
            $user->letter = Pinyin::getChineseInitials($user->name, 'utf-8');
            $user->save();
        }
        return $users;
    }

    public function test(){
        return password_verify('123456', '$2y$10$reXJj8K3ih7P8FFKrTvPLOvo3yYRKAuEf7Z14ol8iK7Ds55BG5Mfa');
    }



}
